const cloud = require('wx-server-sdk');
const axios = require('axios');
cloud.init(
  {
    env: cloud.DYNAMIC_CURRENT_ENV
  }
);
const db = cloud.database();

exports.main = async (event, context) => {
  const code = event.code;
  const phone = event.phone;
  const appId = 'wx7e1b866aaf832906';
  const appSecret = 'b96d2a406af68327e0edd8e1e688065b';
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
  console.log('开始处理登录请求');

  try {
    const res = await axios.get(url);
    const { session_key, openid } = res.data;
    //保存用户信息
    console.log(res)
    if (!session_key || !openid) {
      throw new Error('获取 session_key 或 openid 失败');
    }
    const userCollection = db.collection('user');
    const userResult = await userCollection.where({ phone }).get();
    if (userResult.data.length === 0) {
      // 如果用户不存在，则创建新用户
      await userCollection.add({
        data: {
          phone,
          openid,
          session_key,
          login_status: 1
        }
      });
    } else {
      // 如果用户已存在，则更新用户信息
      await userCollection.where({ phone }).update({
        data: {
          openid,
          session_key,
          login_status: 1
        }
      });
    }

    console.log('用户信息更新成功');
    return {
      success: true,
      openid,
      session_key
    };
  } catch (error) {
    console.error('处理登录请求时发生错误', error);
    return {
      success: false,
      error,
    };
  }
};
